<?php
namespace App\Http\Controllers;
/**
 *
 * 订单控制器
 *
 * @author maqu
 *
 */

use App\Models\GoodsStatistics;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Services\CommissionService;
use App\Services\KuaidiService;
use App\Services\CouponService;
use App\Services\OrderService;
use App\Services\RefundService;
use App\Services\UserAccountService;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

class OrdersController extends BaseController {

    var $_error='';
    
	//列表-所有订单
	/**
	 *
	 * 各分类的产品
	 *
	 * @param nav all/pendding/shipped
	 * @param firstrow
	 * @param pagesize
	 */
	public function lists($user_id){
	
		$firstrow = Input::get('firstrow',0);
		$pagesize = Input::get('pagesize',10);

		$nav =Input::get('nav','all');

		$orderService = new OrderService();

		/* 根据导航获取指定的订单以及订单商品 */
		$user_orders = $orderService->getOrderList($user_id,$nav,$firstrow,$pagesize);
//		dd($user_orders);

		/* 编辑返回数据 */
		$return = [];
		/* 编辑订单数据 */
		foreach($user_orders as $k => $order){

			$order_arr = [
				"order_id" => $order['order_id'],
				"order_sn" => $order['order_sn'],
				"order_name" =>'',
				"seller_id" => $order['seller_id'],
				"seller_name" => $order['seller_name'],
				"extension"  => $order['extension'],
				"status" => $order['status'],
				"status_name" => '',
				"goods_detail" => '',
				"goods_amount" => $order['goods_amount'],
				"shipping_fee" => $order['order_extm']['shipping_fee'],
				"discount" => $order['discount'],
				"order_amount" => $order['order_amount'],
				"add_time" => local_date('Y-m-d H:i:s',$order['add_time']),
				"shipping_name" => $order['order_extm']['shipping_name'],
				"shipping_egname" =>$this->getShippingEg($order['order_extm']['shipping_name']) ,
				"invoice_no" => $order['invoice_no'],
				"goods_count" => 0,
				"refund_status" => 0,
				"order_goods" => [],
				"ican" => [
					"payment" => false,
					"cancel" => false,
					"delete" => false,
					"confirm_order" => false,
					"view_logistics" => false,
					"evaluate" => false,
				],
				"tuan_state" => -1,
				"share_tuan" => [
					"share_tuan_desc" => "",
					"share_tuan_url" => "",
				]

			];

			/* 退款/货商品数据编辑处理 */
			$refund_goods_arr = [];
			if(count($order['refund_goods'])>0){
				foreach($order['refund_goods'] as $i => $refund_goods){
					$refund_goods_arr[$refund_goods['spec_id']] = $refund_goods;
				}
			}

			/* 退款/货单数据编辑处理 */
			$order_refund_arr = [];
			if(count($order['order_refund'])>0){
				foreach($order['order_refund'] as $i => $order_refund){
					$order_refund_arr[$order_refund['refund_id']] = $order_refund;
				}
			}

			$goods_count = 0;
			$detail = '';
			/* 编辑订单商品信息 */
			foreach ($order['order_goods'] as $i => $order_goods){
				$order_goods_arr = [
						"rec_id" => $order_goods['rec_id'],
						"goods_id" => $order_goods['goods_id'],
						"goods_name" => $order_goods['goods_name'],
						"spec_id" => $order_goods['spec_id'],
						"specification" => $order_goods['specification'],
						"price" => $order_goods['price'],
						"market_price" => $order_goods['market_price'],
						"quantity" => $order_goods['quantity'],
						"gstatus_name" => "",
						"goods_image" => "",
//						"orderGoodsIcan" => [
//								"apply_refund" => false,
//								"cancel_refund" => false,
//								"return_goods" => false,
//								"change_expressno" => false,
//						]
				];

				/* 商品总数 */
				$goods_count += $order_goods['quantity'];

				/* 商品状态 */
				$goods_status =  0;
				if(array_key_exists($order_goods['spec_id'],$refund_goods_arr)){
					$order_goods_arr['gstatus_name']
							= $orderService->orderGoodsStatus(
							$order_refund_arr[$refund_goods_arr[$order_goods['spec_id']]['refund_id']]['refund_type'],
							$order_refund_arr[$refund_goods_arr[$order_goods['spec_id']]['refund_id']]['refund_status']);

					$goods_status = $order_refund_arr[$refund_goods_arr[$order_goods['spec_id']]['refund_id']]['refund_status'];
				}

				//判断是否为售后订单
				if($goods_status != REFUND_CANCELED && $goods_status != REFUND_FINISHED){
					$order_arr['refund_status'] = 1;
				}

//				/* 商品可操作按钮 */
//				$order_goods_arr['orderGoodsIcan'] = $orderService->orderGoodsIcan($order['status'],$goods_status);

				/* 商品图片地址编辑 */
				if(!empty($order_goods['goods_image'])){
					$order_goods_arr['goods_image'] = complete_url($order_goods['goods_image']);
				}
				/* 订单详情 */
            	$detail .= $order_goods['goods_name'] . ' + ';

				/* 订单名称（默认为单类商品订单） */
				$order_arr['order_name'] = $order_goods['goods_name'];

				/* 编辑订单商品数据进入订单数据 */
				$order_arr['order_goods'][] = $order_goods_arr;

				unset($order_goods_arr);
			}

			/* 订单内商品总数 */
			$order_arr['goods_count'] = $goods_count;


			switch ($order['extension']){
				case 'normal':

					/* 订单名称（如果是多商品订单，显示名称为多商品购买） */
					if(count($order['order_goods'])>1){
						$order_arr['order_name'] = '多商品购买';
					}

					/* 订单名称详情（使用情景：多类商品订单中） */
					$order_arr['goods_detail'] = substr($detail, 0, -1);

					/* 普通订单状态名 */
					$order_arr['status_name'] = $orderService->orderStatus($order['status'],$order['evaluation_status'],$order['complain_status'],$order['order_id']);
					$order_arr['ican'] = $orderService->orderIcan($order);
					break;
			}

			if($order_arr['refund_status'] == 1){
				$order_arr['status_name'] = '退款退货中';
			}

			$return[] = $order_arr;
			unset($refund_goods_arr);
			unset($order_refund_arr);
			unset($order_arr);
		}

		return $this->success($return);
	}

	//买家-查看订单
	/**
	 * 查看订单
	 *
	 * @param $user_id 用户id
	 * @param $id：订单id
	 */
	public function detail($user_id,$id=0){

		if(!$id){
			return $this->failure('参数不对');
		}

		$orderService = new OrderService();

		//订单基本信息
		$order_info = $orderService->getOrderInfo($user_id,$id);
		if(!$order_info){
			return $this->failure("该订单不存在");
		}
		$order = $order_info->toArray();
		$time = DB::table('config')->where('code','order_info_live_time_goods')->value('value');//未支付订单存活时间商品 配置
		$order_arr = [
			"order_id" => $order['order_id'],
			"order_sn" => $order['order_sn'],
			"seller_id" => $order['seller_id'],
			"seller_name" => $order['seller_name'],
			"order_name" => '',
			"extension"  => $order['extension'],
			"status"	=> $order['status'],
			"status_name" =>'',
			"status_detail" => '',
			"goods_detail" => '',
			"evaluation_status" =>  $order['evaluation_status'],
			"goods_amount" => $order['goods_amount'],
			"discount" => $order['discount'],
			"order_amount" => $order['order_amount'],
			"add_time" => local_date('Y-m-d H:i:s',$order['add_time']),
			"end_time" => $order['add_time'] + $time*60 - gmtime(), //到期时间(秒)
			"shipping_name" => $order['order_extm']['shipping_name'],
			"shipping_egname" => $this->getShippingEg($order['order_extm']['shipping_name']),
			"invoice_no" => $order['invoice_no'],
			"pay_time"=> local_date('Y-m-d H:i:s',$order['pay_time']),
			"postscript" => $order['postscript'],
			"goods_count" => 0,
			"refund_status" => 0,
			"tuan_id" => $order['tuan_id'],
			"pintuan_id" => $order['pintuan_id'],
			"order_extm" =>$order['order_extm'],
			"order_goods" => [],
			"coupon_info" => [
				'coupon_name' => '',
				'coupon_value' => 0,
			],
			"complain"=>[],
			"groupbuy" => [],
			"ican" => [
					"payment" => false,
					"cancel" => false,
					"delete" => false,
					"confirm_order" => false,
					"view_logistics" => false,
					"evaluate" => false,
					"share_tuan" => false,
			],
			"tuan_state" => -1,
			"share_tuan" => [
					"share_tuan_desc" => "",
					"share_tuan_url" => "",
			]
		];
		//是否投诉
		if($order['complain_status'] == 1){
			$complain = DB::table('complain')->where('product_type','goods')->where('order_id',$order['order_id'])->first();

			if($complain->pictures && count($complain->pictures)>0){
				$images = json_decode($complain->pictures,true);
			}
			if (is_array($images) && count($images)>0)
			{
				foreach($images as $image){
					$imagearr[] = complete_url($image);
				}
				$complain->pictures= $imagearr;
			}else{
				$complain->pictures= '';
			}
			$complain->create_at = local_date_ymd($complain->create_at);
			$complain->update_at = local_date_ymd($complain->update_at);
			$order_arr['complain'] = $complain;
		}else{
			$order_arr['complain'] = '';
		}
		/* 团购信息 */
		if ($order['extension'] == 'groupbuy')
		{
			$group_info = DB::table('groupbuy_log')
					->join('groupbuy','groupbuy_log.group_id','=','groupbuy.group_id')
					->where('groupbuy_log.order_id',$id)
					->select('groupbuy.group_id,groupbuy.group_name')->first();

			$order_arr['groupbuy'] = empty($group_info)?[]:(array)$group_info;
		}

		/* 优惠券信息 */
		if(!empty($order['coupon_sn'])){
			$couponService = new CouponService();
			$coupon_info = $couponService->getCouponInfo($order['coupon_sn']);

			if (!empty($coupon_info)){
				if($coupon_info->coupon){
					$order_arr['coupon_info']['coupon_name'] = $coupon_info->coupon->coupon_name;
					$order_arr['coupon_info']['coupon_value'] = $coupon_info->coupon->coupon_value;
				}
			}

		}

		/* 退款/货商品数据编辑处理 */
		$refund_goods_arr = [];
		if(count($order['refund_goods'])>0){
			foreach($order['refund_goods'] as $i => $refund_goods){
				$refund_goods_arr[$refund_goods['spec_id']] = $refund_goods;
			}
		}

		/* 退款/货单数据编辑处理 */
		$order_refund_arr = [];
		if(count($order['order_refund'])>0){
			foreach($order['order_refund'] as $i => $order_refund){
				$order_refund_arr[$order_refund['refund_id']] = $order_refund;
			}
		}

		$goods_count = 0;
		$detail = '';

		/* 编辑订单商品信息 */
		foreach ($order['order_goods'] as $i => $order_goods){
			$order_goods_arr = [
				"rec_id" => $order_goods['rec_id'],
				"goods_id" => $order_goods['goods_id'],
				"goods_name" => $order_goods['goods_name'],
				"spec_id" => $order_goods['spec_id'],
				"specification" => $order_goods['specification'],
				"market_price" => $order_goods['market_price'],
				"price" => $order_goods['price'],
				"quantity" => $order_goods['quantity'],
				"gstatus_name" => "",
				"goods_image" =>$order_goods['goods_image'] ,
				"orderGoodsIcan" => [
					"apply_refund" => false,
					"cancel_refund" => false,
					"return_goods" => false,
					"change_expressno" => false,
				]
			];

			/* 商品总数 */
			$goods_count += $order_goods['quantity'];

			/* 商品状态 */
			$goods_status =  0;
			if(array_key_exists($order_goods['spec_id'],$refund_goods_arr)){
				$order_goods_arr['gstatus_name']
					= $orderService->orderGoodsStatus(
					$order_refund_arr[$refund_goods_arr[$order_goods['spec_id']]['refund_id']]['refund_type'],
					$order_refund_arr[$refund_goods_arr[$order_goods['spec_id']]['refund_id']]['refund_status']);

				$goods_status = $order_refund_arr[$refund_goods_arr[$order_goods['spec_id']]['refund_id']]['refund_status'];
			}

			//判断是否为售后订单
			if($goods_status != REFUND_CANCELED && $goods_status != REFUND_FINISHED){
				$order_arr['refund_status'] = 1;
			}

			/* 商品可操作按钮 */
			$order_goods_arr['orderGoodsIcan'] = $orderService->orderGoodsIcan($order['extension'],$order['status'],$goods_status);

			if(!empty($order_goods['goods_image'])){
				$order_goods_arr['goods_image'] = complete_url($order_goods['goods_image']);
			}
			/* 订单详情 */
			$detail .= $order_goods['goods_name'] . ' + ';

			/* 订单名称（默认为单类商品订单） */
			$order_arr['order_name'] = $order_goods['goods_name'];

			/* 编辑订单商品数据进入订单数据 */
			$order_arr['order_goods'][] = $order_goods_arr;

			unset($order_goods_arr);
		}

		/* 订单内商品总数 */
		$order_arr['goods_count'] = $goods_count;
		/* 订单状态详细描述 */
		$order_arr['status_detail'] = $orderService->orderStatusDetail($order['status'],$order['ship_time'],$order['tuan_id'],$order['extension']);

		switch ($order['extension']){
			case 'normal':

				/* 订单名称（如果是多商品订单，显示名称为多商品购买） */
				if(count($order['order_goods'])>1){
					$order_arr['order_name'] = '多商品购买';
				}

				/* 订单名称详情（使用情景：多类商品订单中） */
				$order_arr['goods_detail'] = substr($detail, 0, -1);

				/* 普通订单状态名 */
				$order_arr['status_name'] = $orderService->orderStatus($order['status'],$order['evaluation_status'],$order['complain_status'],$order['order_id']);
				$order_arr['ican'] = $orderService->orderIcan($order);

				break;

		}

		if($order_arr['refund_status'] == 1){
			$order_arr['status_name'] = '退款退货中';
			$order_arr['status_detail'] = '正在为您处理中，请耐心等待';
		}

		unset($refund_goods_arr);
		unset($order_refund_arr);

		//支付方式列表
		$pay_list = [
			[
				'payment_id'   => 1,
				'payment_name' => '支付宝',
				'payment_code' => 'alipay',
				'chosed'	   => 0,
			],
			[
				'payment_id'   => 2,
				'payment_name' => '微信',
				'payment_code' => 'wxPay',
				'chosed'	   => 0,
			]
		];

		foreach($pay_list as $k =>$item){
			if($item['payment_id'] == $order['payment_id']){
				$pay_list[$k]['chosed'] = 1;
			}
		}

		$order_arr['pay_list'] = $pay_list;
		return $this->success($order_arr);
	}

	public function order_tuan($user_id,$id=0){

		if(!$id){
			return $this->failure('参数不对');
		}

		$orderService = new OrderService();

		//订单基本信息
		$order_info = $orderService->getOrderInfo($user_id,$id);
		if(!$order_info){
			return $this->failure("该订单不存在");
		}

		$order = $order_info->toArray();

		$data = [
			"tuan_id" => $order['tuan_id'],
		];

		return $this->success($data);
	}
    /**
     * 买家取消订单
     * @param $user_id 用户id
     * @param $id：订单id
     * @return mixed
     * @throws Exception
     * @throws \Exception
     */
	public function cancel($user_id,$id=0){

	    if(!$id){
	        return $this->failure('参数不对');
	    }
	    
		$user_info = DB::table('member')->where('user_id',$user_id)->first();

		$orderService = new OrderService();

		//只有待付款的订单可以取消
		$order_info = $orderService->getOrderInfo($user_id,$id);

		if (empty($order_info)){
			return $this->failure('参数不对');
		}

		if($order_info->tuan_id > 0){
			return $this->failure('团购订单不可取消');
		}

		if($order_info->status!=ORDER_PENDING ){
		    return $this->failure('该订单无法取消订单');
		}

		if(count($order_info->orderRefund)>0){
			foreach($order_info->orderRefund as $k => $item){
				if($item->refund_status != REFUND_FINISHED && $item->refund_status != REFUND_CANCELED ){
					return $this->failure('请在退款/货流程结束后再取消订单！');
				}
			}
		}

		DB::beginTransaction();

	 	try {
			$order_info->status = ORDER_CANCELED;		//0表示订单为取消状态

            /* 更新订单状态 */
			$order_info->save();

            //加上订单使用掉的优惠券次数
			if($order_info->coupon_sn){
				DB::table('coupon_sn')->where('coupon_sn',$order_info->coupon_sn)->increment('remain_times',1);
			}

//            /* 加回商品库存 */ 库存减少修改在支付成功后进行 所以现在无库存变化
//            $orderService->changeStock('+',$id);

			/* 添加订单操作日志 订单从代付款->已取消 */
          	$orderService->addOrderLog($id,$user_info->user_name,ORDER_PENDING,ORDER_CANCELED,"买家取消订单");

            /* 发送给卖家订单取消通知 */
            //todo
            
            DB::commit();
            
            return $this->success(null);
            
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }  
	}
	
	/**
     *    删除订单
     *
     *    @author    Garbin
     *    @return    void
     */
    function delete($user_id,$id=0)
    {

	    if(!$id){
	        return $this->failure('参数不对');
	    }

		$user_info = DB::table('member')->where('user_id',$user_id)->first();

		$orderService = new OrderService();

		//只有待付款的订单可以取消
		$order_info = $orderService->getOrderInfo($user_id,$id);

		if (empty($order_info)){
			return $this->failure('参数不对');
		}

		/* 只有已取消或者已退款或者已完成的订单可以删除 */
		if($order_info->status!=ORDER_CANCELED && $order_info->status!=ORDER_REFUND && $order_info->status!=ORDER_FINISHED){
			return $this->failure('该订单不可删除');
		}

		DB::beginTransaction();
        
		try {
			//买家删除标志位 设置为true
			$order_info->delflg_buyer = ORDER_DELETE_NOTE;

			$order_info->save();

			/* 添加订单操作日志 订单->已删除 */
			$orderService->addOrderLog($id,$user_info->user_name,$order_info->status,ORDER_DELETED,"买家删除订单");

	        return $this->success(null);
		} catch (Exception $e) {
			DB::rollback();
			throw $e;
		}	
    }

	/**
	 * 确认收货
	 * @param $user_id
	 * @param int $id
	 * @param CommissionService $commission
	 * @param UserAccountService $user_account
	 * @return mixed
	 * @throws Exception
	 */
	public function confirm($user_id,$id=0,CommissionService $commission,UserAccountService $user_account){

	    if(!$id){
	        return $this->failure('参数不对');
	    }

		$user_info = DB::table('member')->where('user_id',$user_id)->first();
		
		$orderService = new OrderService();

		//只有已发货且无商品处于退款流程的订单可以确认收货
		$order_info = $orderService->getOrderInfo($user_id,$id);
		if (empty($order_info)){
			return $this->failure('参数不对');
		}

		if($order_info->status!=ORDER_SHIPPED ){
			return $this->failure('该订单无法确认收货');
		}

		//判断是否有在退款退货流程中
		if(count($order_info->orderRefund)>0){
			foreach($order_info->orderRefund as $k => $item){
				if($item->refund_status != REFUND_FINISHED && $item->refund_status != REFUND_CANCELED ){
					return $this->failure('该订单有商品处于退货中，无法确认收货');
				}
			}
		}

        DB::beginTransaction();
        
		try {

//			//修改订单信息
			$order_info->status = ORDER_FINISHED;		//40：确认收货，订单完成
			$order_info->finished_time = gmtime();		//结束时间
			$order_info->save();

			foreach($order_info->orderGoods as $og){
			    GoodsStatistics::where('goods_id',$og->goods_id)->increment('sales',$og->quantity);

			}

			/* 记录订单操作日志 订单从已发货->已完成 */
			$orderService->addOrderLog($id,$user_info->user_name,ORDER_SHIPPED,ORDER_FINISHED,"买家确认收货");

			//用户确认收货收益计算
			$account_money = $commission->getCommission($order_info->seller_id,$order_info->order_amount,'goods');
			//平台收益
			$admin_commission = $account_money['franchisee_commission_goods']; //平台收益比例
			$admin_money = 	$account_money['admin_money'];

			//加盟商收益
			$franchisee_commission = $account_money['partner_commission']; //加盟商收益比例
			$franchisee_money = $account_money['franchisee_money'];

			//合伙人收益
			$partner_money = $account_money['partner_money'];

			//账户资金操作  以及记录日志
			if($admin_money > 0 ){
				$user_account->incomeMoney(1,$admin_money,'结算商品订单:订单编号:'.$order_info->order_sn.'分成比例:'.$admin_commission.'%',$order_info->order_id,'goods','+');
			}

			if($franchisee_money > 0 && $account_money['franchisee_id'] > 0){
				$user_account->incomeMoney($account_money['franchisee_id'],$franchisee_money,'结算商品订单:订单编号:'.$order_info->order_sn.'分成比例:'.$franchisee_commission.'%',$order_info->order_id,'goods','+');
			}

			if($partner_money > 0){
				$user_account->incomeMoney($order_info->seller_id,$partner_money,'结算商品订单:订单编号:'.$order_info->order_sn.'',$order_info->order_id,'goods','+');
			}

            DB::commit();
            
			return $this->success(null);
			
		} catch (Exception $e) {
			DB::rollback();
			throw $e;
		}
	}

	//各个订单导航下的数据
	public function allcountlist(){

	    $user_id = Input::get('user_id');

		$orderService = new OrderService();
		$count = $orderService->allcountList($user_id);

	    return $this->success($count);
	}
	
	//买家-退款申请
	/**
	 * 申请退款
	 *
	 * @param $user_id：用户id
	 * @param $order_id：订单id
	 *
	 */	
	public function getApplyRefund($user_id,$order_id){
	
//	    $rec_id = intval(Input::get('rec_id',0));
//
//	    if(!$rec_id){
//	        return $this->failure('参数不对');
//	    }
	    if(!$order_id){
	        return $this->failure('参数不对');
	    }

		$orderService = new OrderService();
		$orderInfo = $orderService->getOrderInfo($user_id,$order_id);

		//判断订单是否存在
		if(!$orderInfo){
			return $this->failure('订单不存在');
		}

		if($orderInfo->tuan_id > 0){
			return $this->failure('拼团订单不可申请退款/货操作');
		}

		//订单状态不是待发货或者待收货，不可以提交退款/货申请
		if(!($orderInfo->status == ORDER_ACCEPTED || $orderInfo->status == ORDER_SHIPPED )){
			return $this->failure('该订单不可退款/货');
		}

		//判断订单商品是否存在
		$spec_id = 0;
		$max_refund_amount = 0;
		foreach($orderInfo->orderGoods as $order_goods){
			if($order_goods->order_id == $order_id){
				$spec_id = $order_goods->spec_id;
				$max_refund_amount = $order_goods->quantity * $order_goods->price;
				break;
			}
		}
		if(!$spec_id){
			return $this->failure('订单商品不存在');
		}

		//判断该商品是否已经处于退款/货流程中了
		$refund_id = 0;
		if($orderInfo->refundGoods){
			foreach($orderInfo->refundGoods as $refund_goods){
				if($refund_goods->spec_id == $spec_id){
					$refund_id = $refund_goods->refund_id;
					break;
				}
			}
		}
		if($refund_id){
			foreach($orderInfo->orderRefund as $order_refund){
				if($order_refund->refund_id == $refund_id){
					if($order_refund->refund_status != REFUND_CANCELED){
						return $this->failure('请不要重复申请');
					}
				}
			}
		}

		$reasons = [
			'订单信息有误/拍错-（未发货）',
			'拒签，延迟收货-（生鲜蔬果不支持）',
			'未收到货',
			'商品质量问题',
			'商品漏发错发',
			'商品与描述不一致',
			'其他'
		];
		
		$result =[
			'reasons' =>$reasons,
			'max_refund_amount' => $max_refund_amount
		];
		
		return $this->success($result);
	}
	
	//买家提交退款/货申请
	/**
	 * 退款
	 *
	 * @param $rec_id：订单商品id
	 */	
	public function postApplyRefund($user_id,$order_id){		

//	    $rec_id = intval(Input::get('rec_id',0));//订单商品id
		//获取页面传递的数据
		$refund_type = Input::get('refund_type',REFUND_TYPE_REFUND);//退款/货类型 1 退款 2 退货
		$refund_reason	= Input::get('refund_reason');//退款理由
		$refund_amount	= Input::get('refund_amount');//退款金额
		$refund_desc	= Input::get('refund_desc');//退款说明

	    if(!$order_id||!$user_id||!$refund_type||!$refund_reason||!$refund_amount){
	        return $this->failure('参数不对');
	    }
//		dd($refund_desc);
		$orderService = new OrderService();
		$orderInfo = $orderService->getOrderInfo($user_id,$order_id);

		//判断订单是否存在
		if(!$orderInfo){
			return $this->failure('订单不存在');
		}

		if($orderInfo->tuan_id > 0){
			return $this->failure('拼团订单不可申请退款/货操作');
		}

		//订单状态不是待发货且不是退款或者待收货且不是退货，则不可以提交退款/货申请
		if(!($orderInfo->status == ORDER_ACCEPTED || $orderInfo->status == ORDER_SHIPPED )){
			return $this->failure('该订单不可退款/货');
		}

		if($orderInfo->status == ORDER_ACCEPTED && $refund_type != REFUND_TYPE_REFUND){
			return $this->failure('该订单不可申请退货');
		}

		if($orderInfo->status == ORDER_SHIPPED && $refund_type != REFUND_TYPE_RETURN_GOODS){
			return $this->failure('该订单不可申请退款');
		}

		//判断订单商品是否存在
		$spec_id = 0;
		$orderGoods = null;
		foreach($orderInfo->orderGoods as $order_goods){
			if($order_goods->order_id == $order_id){
				$spec_id = $order_goods->spec_id;
				$orderGoods = $order_goods;
				break;
			}
		}
		if(!$spec_id){
			return $this->failure('订单商品不存在');
		}

		//判断该商品是否已经处于退款/货流程中了
		$refund_id = 0;
		if($orderInfo->refundGoods){
			foreach($orderInfo->refundGoods as $refund_goods){
				if($refund_goods->spec_id == $spec_id){
					$refund_id = $refund_goods->refund_id;
					break;
				}
			}
		}
		if($refund_id){
			foreach($orderInfo->orderRefund as $order_refund){
				if($order_refund->refund_id == $refund_id){
					if($order_refund->refund_status != REFUND_CANCELED){
						return $this->failure('请不要重复申请');
					}
				}
			}
		}

		if($refund_amount > $orderGoods->price * $orderGoods->quantity){
			return $this->failure("退款金额不能大于该商品总金额");
		}
        DB::beginTransaction();
        
        try{
			$user_info = DB::table('member')->where('user_id',$user_id)->first();
			$user_name = $user_info->user_name;

			//添加或者更新退款/货申请
			$refundService = new RefundService();
			$refundService->addRefund($refund_id,$user_id,$refund_type,$refund_reason,$refund_amount,$refund_desc,$orderInfo,$orderGoods);

    		//添加退款流程操作记录
    		$remark = '退款理由：'.$refund_reason.'退款说明：'.$refund_desc;
			$refundService->addOrderRefundLog($refund_id,$user_name,$refund_type,null,REFUND_PENDING,$remark);

			DB::table('order')
					->where('order_id',$order_id)
					->update([
							'status' => ORDER_REFUNDING,//同意退款 等待退款
					]);

			/* 操作记录 */
			$order_log = [
					'order_id'  => $order_id,
					'operator'  => $user_id,
					'order_status' => '待发货',
					'changed_status' =>'退款中' ,
					'remark'    => '用户申请退款',
					'log_time'  => gmtime(),
			];

			DB::table('order_log')->insert($order_log);
    		DB::commit();
    		return $this->success(null);
        } catch(Exception $e){
			DB::rollback();
			throw $e;
		}
	}

	/**
	 *	取消退款/货
	 * 
	 *  @param $rec_id：商品订单id
	 */
	public function cancelRefund($user_id,$order_id){

//	    $rec_id = intval(Input::get('rec_id',0));
	    if(!$order_id){
	        return $this->failure('参数不对');
	    }
	    
		$user_name = DB::table('member')->where('user_id',$user_id)->pluck('user_name')[0];

		$orderService = new OrderService();
		$orderInfo = $orderService->getOrderInfo($user_id,$order_id);

		//判断订单是否存在
		if(!$orderInfo){
			return $this->failure('订单不存在');
		}

		//订单状态不是待发货或者待收货，不可以提交退款/货申请
		if($orderInfo->status != TOUR_ORDER_REFUNDING){
			return $this->failure('该订单不可取消退款/货');
		}

		//判断订单商品是否存在
		$spec_id = 0;
		foreach($orderInfo->orderGoods as $order_goods){
			if($order_goods->order_id == $order_id){
				$spec_id = $order_goods->spec_id;
				break;
			}
		}
		if(!$spec_id){
			return $this->failure('订单商品不存在');
		}

		//判断该商品是否已经处于退款/货流程中了
		$refund_id = 0;
		if($orderInfo->refundGoods){
			foreach($orderInfo->refundGoods as $refund_goods){
				if($refund_goods->spec_id == $spec_id){
					$refund_id = $refund_goods->refund_id;
					break;
				}
			}
		}
		$orderRefund = null;
		if($refund_id){
			foreach($orderInfo->orderRefund as $order_refund){
				if($order_refund->refund_id == $refund_id){
					$orderRefund = $order_refund;
					if($orderInfo->status == ORDER_ACCEPTED){
						//订单状态不是待发货且不是退款或者待收货且不是退货，则不可以提交退款/货申请
						if(!($order_refund->refund_status == REFUND_PENDING && $order_refund->refund_type == REFUND_TYPE_REFUND)){
							return $this->failure('该订单不可取消退款');
						}
					}
					if($orderInfo->status == ORDER_SHIPPED){
						if(!(($order_refund->refund_status == REFUND_PENDING || $order_refund->refund_status == REFUND_ACCEPTED )&& $order_refund->refund_type == REFUND_TYPE_RETURN_GOODS)){
							return $this->failure('该订单不可取消退货申请');
						}
					}
				}
			}
		}
		
		DB::beginTransaction();
        		
		try{
			//取消退款申请
			$orderRefund->refund_status = REFUND_CANCELED;
			$orderRefund->save();

			//添加记录
			$refundService = new RefundService();
			$remark = "取消退款申请";
			$refundService->addOrderRefundLog($refund_id,$user_name,$orderRefund->refund_type,REFUND_PENDING,REFUND_CANCELED,$remark);

			DB::table('order')
					->where('order_id',$order_id)
					->update([
							'status' => ORDER_ACCEPTED,//待发货
					]);

			/* 操作记录 */
			$order_log = [
					'order_id'  => $order_id,
					'operator'  => $user_name,
					'order_status' => '退款中',
					'changed_status' =>'待发货' ,
					'remark'    => '用户取消退款',
					'log_time'  => gmtime(),
			];

			DB::table('order_log')->insert($order_log);

			DB::commit();
			
			return $this->success(null);
				
		}catch(Exception $e){
			DB::rollback();
				throw $e;
		}		
	
	}

	//买家-退货
	/**
	 *	退货
	 *
	 *  @param $rec_id：商品订单id
	 */
	public function getReturnGoods($user_id,$order_id){
		$rec_id = intval(Input::get('rec_id',0));

		if(!$rec_id||!$user_id){
			return $this->failure('参数不对');
		}

		$orderService = new OrderService();
		$orderInfo = $orderService->getOrderInfo($user_id,$order_id);

		//判断订单是否存在
		if(!$orderInfo){
			return $this->failure('订单不存在');
		}

		if($orderInfo->tuan_id > 0){
			return $this->failure('拼团订单不可申请退款/货操作');
		}

		//订单状态不是待收货，不可以退货
		if($orderInfo->status != ORDER_SHIPPED ){
			return $this->failure('该订单不可退货');
		}

		//判断订单商品是否存在
		$spec_id = 0;
		foreach($orderInfo->orderGoods as $order_goods){
			if($order_goods->rec_id == $rec_id){
				$spec_id = $order_goods->spec_id;
				break;
			}
		}
		if(!$spec_id){
			return $this->failure('订单商品不存在');
		}

		//判断该商品是否已经处于退款/货流程中了
		$refund_id = 0;
		if($orderInfo->refundGoods){
			foreach($orderInfo->refundGoods as $refund_goods){
				if($refund_goods->spec_id == $spec_id){
					$refund_id = $refund_goods->refund_id;
					break;
				}
			}
		}
		$orderRefund = null;
		if($refund_id){
			foreach($orderInfo->orderRefund as $order_refund){
				if($order_refund->refund_id == $refund_id){
					$orderRefund = $order_refund;
					//订单状态待收货且不是退货，则不可以提交退款/货申请
					if(!($order_refund->refund_status == REFUND_ACCEPTED && $order_refund->refund_type == REFUND_TYPE_RETURN_GOODS)){
						return $this->failure('该订单无法进行商品退货');
					}
				}
			}
		}

		$express_company = DB::table('express_company')->orderBy('id','asc')->select("code","name")->get();

		return $this->success($express_company);
	}
	
    //买家-退货
	/**
	 *	退货
	 * 
	 * @param $rec_id：商品订单id
	 * @param $refund_invoice：快递公司code
	 * @param $refund_invoice_no：运单号
	 */
	public function postReturnGoods($user_id,$order_id){
	    $rec_id = intval(Input::get('rec_id',0));

		//获取页面传递的数据
		$refund_invoice = Input::get('refund_invoice');
		$refund_invoice_no	= Input::get('refund_invoice_no');

		if(!$rec_id||!$user_id||!$refund_invoice||!$refund_invoice_no){
			return $this->failure('参数不对');
		}

		$user_name = DB::table('member')->where('user_id',$user_id)->pluck('user_name');

		$orderService = new OrderService();
		$orderInfo = $orderService->getOrderInfo($user_id,$order_id);

		//判断订单是否存在
		if(!$orderInfo){
			return $this->failure('订单不存在');
		}

		if($orderInfo->tuan_id > 0){
			return $this->failure('拼团订单不可申请退款/货操作');
		}

		//订单状态不是待收货，不可以退货
		if($orderInfo->status != ORDER_SHIPPED ){
			return $this->failure('该订单不可退货');
		}

		//判断订单商品是否存在
		$spec_id = 0;
		foreach($orderInfo->orderGoods as $order_goods){
			if($order_goods->rec_id == $rec_id){
				$spec_id = $order_goods->spec_id;
				break;
			}
		}
		if(!$spec_id){
			return $this->failure('订单商品不存在');
		}

		//判断该商品是否已经处于退款/货流程中了
		$refund_id = 0;
		if($orderInfo->refundGoods){
			foreach($orderInfo->refundGoods as $refund_goods){
				if($refund_goods->spec_id == $spec_id){
					$refund_id = $refund_goods->refund_id;
					break;
				}
			}
		}
		$orderRefund = null;
		if($refund_id){
			foreach($orderInfo->orderRefund as $order_refund){
				if($order_refund->refund_id == $refund_id){
					$orderRefund = $order_refund;
					//订单状态待收货且不是退货，则不可以提交退款/货申请
					if(!($order_refund->refund_status == REFUND_ACCEPTED && $order_refund->refund_type == REFUND_TYPE_RETURN_GOODS)){
						return $this->failure('该订单无法进行商品退货');
					}
				}
			}
		}

		DB::beginTransaction();
        		
		try{

			$orderRefund->refund_status = REFUND_SHIPPED;
			$orderRefund->refund_ship_time = gmtime();
			$orderRefund->refund_invoice = $refund_invoice;
			$orderRefund->refund_invoice_no = $refund_invoice_no;
			$orderRefund->save();


			//添加记录
			$refundService = new RefundService();
			$remark = '退货 快递:'.$refund_invoice. ' 快递单号:'.$refund_invoice_no;
			$refundService->addOrderRefundLog($refund_id,$user_name,$orderRefund->refund_type,REFUND_ACCEPTED,REFUND_SHIPPED,$remark);

			DB::commit();
			
			return $this->success(null);
				
		}catch(Exception $e){
			DB::rollback();
				throw $e;
		}			
	}

	//买家-修改单号
	/**
	 *	修改单号
	 *
	 *  @param $rec_id：商品订单id
	 */
	public function getModifyExpress($user_id,$order_id){
		$rec_id = intval(Input::get('rec_id',0));

		if(!$rec_id||!$user_id){
			return $this->failure('参数不对');
		}

		$orderService = new OrderService();
		$orderInfo = $orderService->getOrderInfo($user_id,$order_id);

		//判断订单是否存在
		if(!$orderInfo){
			return $this->failure('订单不存在');
		}

		if($orderInfo->tuan_id > 0){
			return $this->failure('无权限操作');
		}

		//订单状态不是待收货，不可以退货
		if($orderInfo->status != ORDER_SHIPPED ){
			return $this->failure('无权限操作');
		}

		//判断订单商品是否存在
		$spec_id = 0;
		foreach($orderInfo->orderGoods as $order_goods){
			if($order_goods->rec_id == $rec_id){
				$spec_id = $order_goods->spec_id;
				break;
			}
		}
		if(!$spec_id){
			return $this->failure('订单商品不存在');
		}

		//判断该商品是否已经处于退款/货流程中了
		$refund_id = 0;
		if($orderInfo->refundGoods){
			foreach($orderInfo->refundGoods as $refund_goods){
				if($refund_goods->spec_id == $spec_id){
					$refund_id = $refund_goods->refund_id;
					break;
				}
			}
		}
		$orderRefund = null;
		if($refund_id){
			foreach($orderInfo->orderRefund as $order_refund){
				if($order_refund->refund_id == $refund_id){
					$orderRefund = $order_refund;

					//退货订单状态待收货且不是退货，则不可以修改物流信息
					if(!($order_refund->refund_status == REFUND_SHIPPED && $order_refund->refund_type == REFUND_TYPE_RETURN_GOODS)){
						return $this->failure('无权限修改退货物流信息');
					}
				}
			}
		}

		$express_company = DB::table('express_company')->orderBy('id','asc')->select("code","name")->get();

		$result = [
			'rec_id' => $rec_id,
			'refund_invoice' => $orderRefund->refund_invoice,
			'refund_invoice_no' => $orderRefund->refund_invoice_no,
			'express_company' =>$express_company
		];

		return $this->success($result);
	}

	//买家-修改单号
	/**
	 *	修改单号
	 * 
	 *  @param $rec_id：商品订单id
	 */
	public function postModifyExpress($user_id,$order_id){
	    $rec_id = intval(Input::get('rec_id',0));

		//获取页面传递的数据
		$refund_invoice = Input::get('refund_invoice');
		$refund_invoice_no	= Input::get('refund_invoice_no');

		if(!$rec_id||!$user_id||!$refund_invoice||!$refund_invoice_no){
			return $this->failure('参数不对');
		}

		$user_name = DB::table('member')->where('user_id',$user_id)->pluck('user_name');

		$orderService = new OrderService();
		$orderInfo = $orderService->getOrderInfo($user_id,$order_id);

		//判断订单是否存在
		if(!$orderInfo){
			return $this->failure('订单不存在');
		}

		//订单状态不是待收货，不可以退货
		if($orderInfo->status != ORDER_SHIPPED ){
			return $this->failure('无权限操作');
		}

		//判断订单商品是否存在
		$spec_id = 0;
		foreach($orderInfo->orderGoods as $order_goods){
			if($order_goods->rec_id == $rec_id){
				$spec_id = $order_goods->spec_id;
				break;
			}
		}
		if(!$spec_id){
			return $this->failure('订单商品不存在');
		}

		//判断该商品是否已经处于退款/货流程中了
		$refund_id = 0;
		if($orderInfo->refundGoods){
			foreach($orderInfo->refundGoods as $refund_goods){
				if($refund_goods->spec_id == $spec_id){
					$refund_id = $refund_goods->refund_id;
					break;
				}
			}
		}
		$orderRefund = null;
		if($refund_id){
			foreach($orderInfo->orderRefund as $order_refund){
				if($order_refund->refund_id == $refund_id){
					$orderRefund = $order_refund;

					//退货订单状态待收货且不是退货，则不可以修改物流信息
					if(!($order_refund->refund_status == REFUND_SHIPPED && $order_refund->refund_type == REFUND_TYPE_RETURN_GOODS)){
						return $this->failure('无权限修改退货物流信息');
					}
				}
			}
		}

		DB::beginTransaction();
        		
		try{
			$orderRefund->refund_ship_time = gmtime();
			$orderRefund->refund_invoice = $refund_invoice;
			$orderRefund->refund_invoice_no = $refund_invoice_no;
			$orderRefund->save();

			//添加记录
			$refundService = new RefundService();
			$remark = '修改快递单号 快递:'.$refund_invoice. ' 快递单号:'.$refund_invoice;
			$refundService->addOrderRefundLog($refund_id,$user_name,$orderRefund->refund_type,REFUND_SHIPPED,REFUND_SHIPPED,$remark);

			DB::commit();
			
			return $this->success(null);
				
		}catch(Exception $e){
			DB::rollback();
				throw $e;
		}	
	}

	//列表-所有订单
	/**
	 *
	 * 各分类的产品
	 *
	 * @param nav all/pendding/shipped
	 * @param firstrow
	 * @param pagesize
	 */
	public function afterSaleList($user_id){

		$firstrow = Input::get('firstrow',0);
		$pagesize = Input::get('pagesize',10);

		$refundService = new RefundService();
		$afterSaleList = $refundService->getRefundList($user_id,$firstrow,$pagesize);

		/* 编辑返回数据 */
		$return = [];
		$orderService = new OrderService();
		/* 编辑订单数据 */
		foreach($afterSaleList as $k => $refundorder){

			$refund_order_arr = [
				"refund_id" => $refundorder['refund_id'],
				"apply_date" => $refundorder['apply_date'],
				"order_id" => $refundorder['order_id'],
				"order_sn" => $refundorder['order']['order_sn'],
				"order_name" =>'',
				"status" => $refundorder['refund_status'],
				"status_name" => '',
				"order_amount" => $refundorder['order']['order_amount'],
				"refund_amount" => $refundorder['refund_fee'],
				"order_goods" => [
					"rec_id" => $refundorder['refund_goods']['order_goods']['rec_id'],
					"goods_id" => $refundorder['refund_goods']['order_goods']['goods_id'],
					"goods_name" => $refundorder['refund_goods']['order_goods']['goods_name'],
					"spec_id" => $refundorder['refund_goods']['order_goods']['spec_id'],
					"specification" => $refundorder['refund_goods']['order_goods']['specification'],
					"price" => $refundorder['refund_goods']['order_goods']['price'],
					"quantity" => $refundorder['refund_goods']['order_goods']['quantity'],
					"goods_image" => "",
					"orderGoodsIcan" => [
						"apply_refund" => false,
						"cancel_refund" => false,
						"return_goods" => false,
						"change_expressno" => false,
					]
				],
			];

			/* 退款/货单状态名 */
			$refund_order_arr['status_name'] = $refundService->refundStatus($refundorder['refund_type'],$refundorder['refund_status']);

			/* 订单名称（如果是多商品订单，显示名称为多商品购买） */
			$refund_order_arr['order_name'] = $refundorder['refund_goods']['order_goods']['goods_name'];

			/* 商品可操作按钮 */
			$refund_order_arr['order_goods']['orderGoodsIcan'] = $orderService->orderGoodsIcan($refundorder['order']['extension'],$refundorder['order']['status'],$refundorder['refund_status']);


			/* 商品图片地址编辑 */
			if(!empty($refundorder['refund_goods']['order_goods']['goods_image'])){
				$refund_order_arr['order_goods']['goods_image'] = complete_url($refundorder['refund_goods']['order_goods']['goods_image']);
			}

			/* 编辑订单商品数据进入订单数据 */
			$return[] = $refund_order_arr;
		}

		return $this->success($return);
	}

	//支付订单
	/**
	 * 支付订单
	 *
	 * @param $id：订单id
	 */
	public function pay($id){
	
	    if(!$id){	        
	        return $this->failure('参数不对');
	    }
	}
	
	//查看物流
	/**
	 * 查看物流
	 *
	 * @param $user_id 用户id
	 * @param $id 订单id
	 */
	public function expressHistory($user_id,$id){
	
	    if(!$id){
	        return $this->failure('参数不对');
	    }
	    
		//只有订单状态为已发货，已收货时才可以查看物流
		$query = Order::where('order_id', $id)
    		->where('status', ORDER_SHIPPED)//30：已发货
    		->orWhere('status', ORDER_FINISHED)//40：已收货，订单完成
    		->where('buyer_id',$user_id)
			->with('orderExtm');
    		
		$order = $query->first();

		if (empty($order)){
			return $this->failure('参数不对');
		}

		$shipping_name = DB::table('shipping')->where('shipping_id',$order->orderExtm->shipping_id)->pluck('shipping_egname');
		$kuaidi100Service = new KuaidiService();
		//TODO
		$kuaidi100Service->getHistory($order->invoice_no,$shipping_name);
	}
	
	//评价
	public function getEvaluate($user_id,$id){

	    if($id == 0){
	        return $this->failure('参数不对');
	    }

		$orderService = new OrderService();
		//订单基本信息
		$order_info = $orderService->getOrderInfo($user_id,$id);

		if(!$order_info){
			return $this->failure("该订单不存在");
		}

		if($order_info->status != ORDER_FINISHED){
			return $this->failure("该订单不可评价");
		}

		if($order_info->evaluation_status == EVALUATE_YES){
			return $this->failure("该订单已评价过，不可重复评价");
		}

		$return = [
			'order_info' => [
				'order_id' => $order_info->order_id,
				'order_sn' => $order_info->order_sn
			],
			'order_goods' => []
		];

		//编辑订单商品信息，已经退款/货商品不需要评价
		foreach ($order_info->orderGoods as $i => $order_goods){
			$order_goods_arr = [
					"rec_id" => $order_goods->rec_id,
					"goods_id" => $order_goods->goods_id,
					"goods_name" => $order_goods->goods_name,
					"spec_id" => $order_goods->spec_id,
					"specification" => $order_goods->specification,
					"price" => $order_goods->price,
					"quantity" => $order_goods->quantity,
					"goods_image" => "",
			];
			if(!empty($order_goods->goods_image)){
				$order_goods_arr['goods_image'] = complete_url($order_goods->goods_image);
			}

			$return['order_goods'][$order_goods->rec_id] = $order_goods_arr;
			unset($order_goods_arr);
		}

		foreach($order_info->refundGoods as $i => $refund_goods){
			if($refund_goods->refund_status != REFUND_CANCELED){
				unset($return['order_goods'][$refund_goods->order_goods_id]);
			}
		}

		$return['order_goods'] = array_values($return['order_goods']);

		return $this->success($return);

	}

	//评价
	public function postEvaluate($user_id,$id){
		
		if($id == 0){
			return $this->failure('参数不对');
		}

		$orderService = new OrderService();
		//订单基本信息
		$order_info = $orderService->getOrderInfo($user_id,$id);

		if(!$order_info){
			return $this->failure("该订单不存在");
		}

		if($order_info->status != ORDER_FINISHED){
			return $this->failure("该订单不可评价");
		}

		if($order_info->evaluation_status == EVALUATE_YES){
			return $this->failure("该订单已评价过，不可重复评价");
		}
		foreach ($order_info->orderGoods as $i => $order_goods){
			$rec_id_arr[] = $order_goods->rec_id;//订单商品
		}
//
		$evaluation_arr = Input::get("evaluation");//星级
		if(!$evaluation_arr){
			return $this->failure("评分不能为空！");
		}
		$comment_arr = Input::get("comment");//评论
		$evaluation_images_arr = Input::get('evaluation_images');
		$anonymous = Input::get("anonymous",0);//是否匿名
		//上传评论图片
		$evaluation_images = '';

		if($evaluation_images_arr && count($evaluation_images_arr)>0){
//					if(!array_key_exists($rec_id,$evaluation_images_arr)){
//						continue;
//					}
//					$images = explode(',',$evaluation_images_arr);
			//dd($evaluation_images_arr);
			if(count($evaluation_images_arr)>0){

				foreach($evaluation_images_arr as $i => $image){
					$temps = explode(',',$image);
					$img = base64_decode($temps[1]);
					$filepath = '/data/evaluation/'.$id.'/' ;
					$filename = $filepath . $i . '_'.gmtime() . '.jpg';
					Storage::disk()->put($filename,$img);
					$evaluation_images[]=$filename;
				}
			}else{
				$evaluation_images='';
			}
		}else{
			$evaluation_images='';
		}

		//更新商品评论
		if(is_array($rec_id_arr)) {
			foreach ($rec_id_arr as $rec_id) {
				$ordergoods = OrderGoods::find($rec_id);
				$ordergoods->evaluation = $evaluation_arr;
				$ordergoods->comment = $comment_arr;
				$ordergoods->evaluation_time = gmtime();
				$ordergoods->evaluation_image = count($evaluation_images)> 0 ? json_encode($evaluation_images):'';
				$ordergoods->save();
			}
		}
		$order_info->evaluation_status = EVALUATE_YES;
		$order_info->evaluation_time = gmtime();
		$order_info->anonymous = $anonymous;

		$order_info->save();

		$gpa = DB::table('order_goods')
				->leftJoin('order', 'order_goods.order_id', '=', 'order.order_id')
				->where('goods_id',$ordergoods->goods_id)
				->where('order.evaluation_status',1)
				->avg('evaluation');
		GoodsStatistics::where('goods_id', $ordergoods->goods_id)->increment('comments');
		GoodsStatistics::where('goods_id', $ordergoods->goods_id)->update(array('gpa'=>$gpa));
		//获取对应商品所在地区名称
		$goods_info = DB::table('goods')->where('goods_id',$ordergoods->goods_id)->first();
		//评论数据入库用于乡粉分享
		$full_evaluation = array(
				'item_id'  => $ordergoods->goods_id,
				'user_id'  => $user_id,
				'evaluation_comment'    => $ordergoods->comment,
				'pictures'  => $ordergoods->evaluation_image,
				'evaluation_time'  => $ordergoods->evaluation_time,
				'evaluation_type'  => 'goods',
				'item_name'=>$goods_info->goods_name,
				'province'=>$goods_info->province,
				'city'=>$goods_info->city,
				'country'=>$goods_info->country,
		);
		DB::table('full_evaluation')->insert($full_evaluation);
		return $this->success(null);

	}

	//投诉
	public function complain($user_id,$id, OrderService $OrderService){
		if(!$user_id){
			return $this->failure('请先登录');
		}
		if(!$id){
			return $this->args_invalid();
		}

		$link_name = Input::get('link_name');
		$link_phone = Input::get('link_phone');

		if(!$link_name){
			return $this->failure('请填写联系人');
		}

		if(!$link_phone){
			return $this->failure('请填写联系号码');
		}

		if(!is_mobile($link_phone)){
			return $this->failure('请填写正确的手机号码');
		}

		$comment = Input::get("comment");//描述

		$complain_images_arr = Input::get('complain_images');
		//处理上传的图片
		$complain_images = [];
		if(count($complain_images_arr)>0){
			foreach($complain_images_arr as $i => $image){
				$temps = explode(',',$image);
				$img = base64_decode($temps[1]);
				$filepath = '/data/goods_complain/' . local_date_ymd(gmtime()) .'/' ;
				$filename = $filepath . 'complain_'.$i.'_'.gmtime() .'.jpg';
				Storage::disk()->put($filename,$img);
				$complain_images[]=$filename;
			}
		}

		$OrderService->complainGoodsOrder($user_id,$id,$link_name,$link_phone,$comment,$complain_images,'goods',true);
	}

	//--------------------------------------------------add by yangxy --------------
	//ADd 获取快递公司对应英文名
	public function getShippingEg($shipping)
	{
		switch ($shipping){
			case "EMS经济快递"://后台中显示的快递公司名称
				$postcom = 'ems';//快递公司代码
				break;
			case "EMS":
				$postcom = 'ems';
				break;
			case "邮政快递包裹":
				$postcom = 'ems';
				break;
			case "申通快递":
				$postcom = 'shentong';
				break;
			case "圆通速递":
				$postcom = 'yuantong';
				break;
			case "顺丰速递":
				$postcom = 'shunfeng';
				break;
			case "天天快递":
				$postcom = 'tiantian';
				break;
			case "韵达快递":
				$postcom = 'yunda';
				break;
			case "中通快递":
				$postcom = 'zhongtong';
				break;
			case "龙邦快递":
				$postcom = 'longbanwuliu';
				break;
			case "宅急送":
				$postcom = 'zhaijisong';
				break;
			case "全一快递":
				$postcom = 'quanyikuaidi';
				break;
			case "汇通速递":
				$postcom = 'huitongkuaidi';
				break;
			case "民航快递":
				$postcom = 'minghangkuaidi';
				break;
			case "亚风速递":
				$postcom = 'yafengsudi';
				break;
			case "快捷速递":
				$postcom = 'kuaijiesudi';
				break;
			case "华宇物流":
				$postcom = 'tiandihuayu';
				break;
			case "中铁快运":
				$postcom = 'zhongtiewuliu';
				break;
			/* 修改 by www.68ecshop.com start */
			case "百世汇通":
				$postcom = 'huitongkuaidi';
				break;
			case "全峰快递":
				$postcom = 'quanfengkuaidi';
				break;
			case "德邦":
				$postcom = 'debangwuliu';
				break;
			/* 修改 by www.68ecshop.com end */
			case "FedEx":
				$postcom = 'fedex';
				break;
			case "UPS":
				$postcom = 'ups';
				break;
			case "DHL":
				$postcom = 'dhl';
				break;
			default:
				$postcom = '';
		}
		return $postcom;
	}

}